<template>
  <el-card>
    <el-row justify="space-between">
      <el-col :span="16">
        <el-form inline :model="searchParams">
          <el-form-item label="账号状态">
            <el-select
              v-model="searchParams.status"
              :empty-values="[null, undefined]"
              placeholder="全部"
              style="min-width: 160px"
            >
              <el-option label="全部" value="" />
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="员工姓名">
            <el-input
              v-model="searchParams.name"
              placeholder="请输入员工姓名"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="getEmpployeePage()"
              >搜索</el-button
            >
            <el-button type="info" @click="goReset()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8" style="text-align: right">
        <el-button type="primary" @click="onEmployeeAdd">创建员工</el-button>
        <el-button type="warning" @click="onResetPasswordBatch">
          重置密码
        </el-button>
      </el-col>
    </el-row>

    <!-- 以下是表格 -->
    <el-row>
      <el-col>
        <el-table
          :data="empployeeList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            label="序号"
            type="index"
            :index="getIndex"
            width="80"
          />
          <el-table-column
            label="员工姓名"
            align="center"
            prop="name"
          ></el-table-column>
          <el-table-column
            label="账号"
            align="center"
            prop="username"
          ></el-table-column>
          <el-table-column label="头像" align="center" width="100">
            <template #default="{ row }">
              <el-image
                style="width: 55px; height: 55px"
                :src="
                  row.avatar
                    ? '/api/common/download?name=' + row.avatar
                    : defaultAvatar
                "
                fit="fill"
              />
            </template>
          </el-table-column>
          <el-table-column label="账号状态" align="center" prop="status">
            <template #default="scope">
              <span :class="{ 'disable-color': scope.row.status !== 1 }">{{
                scope.row.status === 1 ? '启用' : '禁用'
              }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="updateTime"
            label="修改时间"
            align="center"
            width="200px"
          >
            <template #default="scope">
              {{ scope.row.updateTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-button @click="onOpenDetail(scope.row)"> 查看 </el-button>
              <!-- <el-button
                size="small"
                type="primary"
                @click="onEditEmployee(scope.row)"
              >
                编辑
              </el-button> 
              -->
              <el-button
                :type="scope.row.status === 1 ? 'info' : 'success'"
                @click="onEmployeeStatusChange(scope.row)"
                v-if="scope.row.username !== 'admin'"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 以下是分页 -->
    <el-row>
      <el-col>
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="->,total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </el-col>
    </el-row>
  </el-card>

  <EmployeeAddEdit
    ref="employeeAddEditRef"
    @empAddEditSuccess="onAddEditSuccess"
  />

  <EmployeeDetail ref="employeeDetailRef" />
</template>

<script setup>
import defaultAvatar from '@/assets/icons/default.png'
import { ref, onMounted } from 'vue'
import EmployeeDetail from '@/views/employee/EmployeeDetail.vue'
import {
  reqGetEmpployeePage,
  reqUpdateEmployeeStatus,
  reqResetEmployeePasswd
} from '@/api/employee'
import EmployeeAddEdit from '@/views/employee/EmployeeAddEdit.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

//条件搜索
const searchParams = ref({
  page: 1,
  pageSize: 5, //默认是5
  name: '', //员工姓名（不是username）
  status: '' //状态，1-启用
})

// 改变pageSize
const handleSizeChange = () => {
  getEmpployeePage()
}
// 改变pageNo
const handleCurrentChange = () => {
  getEmpployeePage()
}

//动态地获取表格的序号列
const getIndex = (index) => {
  console.log('索引数下标', index)
  let nowPage = searchParams.value.page //当前第几页，根据组件取值即可
  let nowLimit = searchParams.value.pageSize //当前每页显示几条，根据组件取值即可
  return index + 1 + (nowPage - 1) * nowLimit // 这里可以理解成一个公式
}

//分页
const total = ref(0)
//分页查询员工列表
const empployeeList = ref([])
const getEmpployeePage = async () => {
  const res = await reqGetEmpployeePage(searchParams.value)
  // console.log(res.data)
  empployeeList.value = res.data.data.records
  total.value = res.data.data.total
}

//onMounted
onMounted(() => {
  getEmpployeePage()
})

//新增员工
const employeeAddEditRef = ref(null)
const onEmployeeAdd = () => {
  employeeAddEditRef.value.openDialog()
}
const onAddEditSuccess = () => {
  // 新增员工成功，重新加载列表
  getEmpployeePage()
}

//编辑员工
const onEditEmployee = (employee) => {
  employeeAddEditRef.value.openDialog(employee)
}

//改变员工的账号状态
const onEmployeeStatusChange = async (employee) => {
  const res = await reqUpdateEmployeeStatus({
    id: employee.id,
    status: Number(!employee.status)
  })
  if (res.data.code === 200) {
    ElMessage.success(res.data.msg || '修改状态成功！')
    getEmpployeePage()
  } else {
    ElMessage.error(res.data.msg || '修改状态失败！')
  }
}

//重置自己密码
// const onResetEmployeePasswd = async (employee) => {
//   ElMessageBox.confirm(
//     '要重置【' + employee.name + '】的密码为123456?',
//     '警告',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning'
//     }
//   )
//     .then(async () => {
//       const res = await reqResetEmployeePasswd(employee)
//       if (res.data.code === 200) {
//         ElMessage.success(
//           res.data.msg || employee.name + '的密码已重置为123456！'
//         )
//       } else {
//         ElMessage.error(res.data.msg || '重置密码失败！')
//       }
//     })
//     .catch(() => {
//       ElMessage({
//         type: 'info',
//         message: '取消操作'
//       })
//     })
// }

// 处理表格多选
const employeeIdSelections = ref([])
const handleSelectionChange = (items) => {
  console.log(items)
  // items中是包含了多个employee数据的数组，
  // 下面将从items中取出每个employee的id存入employeeIdSelections中
  employeeIdSelections.value = []
  items.forEach((item) => {
    employeeIdSelections.value.push(item.id)
  })
}

// 批量重置密码的函数
const onResetPasswordBatch = async () => {
  if (employeeIdSelections.value.length > 0) {
    const res = await reqResetEmployeePasswd(employeeIdSelections.value)
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg || '密码修改成功')
      //重新获取列表
      getEmpployeePage()
    }
  } else {
    ElMessage.warning('请选择员工')
  }
}

//查看详情
const employeeDetailRef = ref(null)
const onOpenDetail = (emp) => {
  console.log(emp)
  employeeDetailRef.value.open(emp)
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.disable-color {
  color: red;
}
</style>
